package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpAutoCollectProductTemporary;
import com.erp.gather.domain.bo.ErpAutoCollectProductTemporaryBo;
import com.erp.gather.domain.vo.ErpAutoCollectProductTemporaryVo;
import com.erp.gather.mapper.ErpAutoCollectProductTemporaryMapper;
import com.erp.gather.service.IErpAutoCollectProductTemporaryService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自动化公共产品临时Service业务层处理
 *
 * @author erp
 * @date 2024-01-10
 */
@RequiredArgsConstructor
@Service
public class ErpAutoCollectProductTemporaryServiceImpl implements IErpAutoCollectProductTemporaryService {

    private final ErpAutoCollectProductTemporaryMapper baseMapper;

    /**
     * 查询自动化公共产品临时
     */
    @Override
    public ErpAutoCollectProductTemporaryVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询自动化公共产品临时列表
     */
    @Override
    public TableDataInfo<ErpAutoCollectProductTemporaryVo> queryPageList(ErpAutoCollectProductTemporaryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpAutoCollectProductTemporary> lqw = buildQueryWrapper(bo);
        Page<ErpAutoCollectProductTemporaryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询自动化公共产品临时列表
     */
    @Override
    public List<ErpAutoCollectProductTemporaryVo> queryList(ErpAutoCollectProductTemporaryBo bo) {
        LambdaQueryWrapper<ErpAutoCollectProductTemporary> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpAutoCollectProductTemporary> buildQueryWrapper(ErpAutoCollectProductTemporaryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpAutoCollectProductTemporary> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCollectProductId() != null, ErpAutoCollectProductTemporary::getCollectProductId, bo.getCollectProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpAutoCollectProductTemporary::getProductPrice, bo.getProductPrice());
        lqw.eq(bo.getBrandId() != null, ErpAutoCollectProductTemporary::getBrandId, bo.getBrandId());
        lqw.eq(bo.getCategoryId() != null, ErpAutoCollectProductTemporary::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getCategoryAncestors() != null, ErpAutoCollectProductTemporary::getCategoryAncestors, bo.getCategoryAncestors());
        lqw.eq(bo.getTemplateId() != null, ErpAutoCollectProductTemporary::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getProductStatus() != null, ErpAutoCollectProductTemporary::getProductStatus, bo.getProductStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getClassifyLabel()), ErpAutoCollectProductTemporary::getClassifyLabel, bo.getClassifyLabel());
        return lqw;
    }

    /**
     * 新增自动化公共产品临时
     */
    @Override
    public Boolean insertByBo(ErpAutoCollectProductTemporaryBo bo) {
        ErpAutoCollectProductTemporary add = BeanUtil.toBean(bo, ErpAutoCollectProductTemporary.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改自动化公共产品临时
     */
    @Override
    public Boolean updateByBo(ErpAutoCollectProductTemporaryBo bo) {
        ErpAutoCollectProductTemporary update = BeanUtil.toBean(bo, ErpAutoCollectProductTemporary.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpAutoCollectProductTemporary entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除自动化公共产品临时
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<Object> initializeLibrary(String categoryId) {
        List<ErpAutoCollectProductTemporary> temporaryList = baseMapper.getInitializeLibraryList(categoryId);
//        Map<Long ,Object> map = new HashMap<>();
//        for (ErpAutoCollectProductTemporary temorary : temporaryList) {
//            map.put(temorary.getCollectProductId(),temorary);
//        }
//        //生成新生成临时表
//        List<Long> newIds = temporaryList.stream()
//                .map(ErpAutoCollectProductTemporary::getId) // 假设getId是获取id的方法
//                .collect(Collectors.toList());
//        //获取已经临时表中已经存在的数据
//        List<ErpAutoCollectProductTemporary> queryTemporaryList = baseMapper.getInitializeLibraryListByCollectId(newIds);
//        List<Long> oldIds = queryTemporaryList.stream()
//                .map(ErpAutoCollectProductTemporary::getId) // 假设getId是获取id的方法
//                .collect(Collectors.toList());
//        //取两者的非交集进行批量插入
//        List<Long> nonIntersecting = newIds.stream()
//                .filter(num -> !oldIds.contains(num)) // 过滤出在list2中不存在的元素
//                .collect(Collectors.toList());
        if (temporaryList.size() > 0) {


            for (ErpAutoCollectProductTemporary product : temporaryList) {
                product.setProductType(0);
                ErpAutoCollectProductTemporary sel = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpAutoCollectProductTemporary>().eq(ErpAutoCollectProductTemporary::getCollectProductId, product.getCollectProductId())
                );
                if (ObjectUtils.isNull(sel)) {
                    baseMapper.insert(product);
                }
            }
        }
        return R.ok("执行完毕，插入" + temporaryList.size() + "条数据");
    }

    @Override
    public R<Object> initializeLibraryByUnshelf(String categoryId) {
        List<ErpAutoCollectProductTemporary> temporaryList = baseMapper.getInitializeLibraryListByUnshelf(categoryId);
//        Map<Long ,Object> map = new HashMap<>();
//        for (ErpAutoCollectProductTemporary temorary : temporaryList) {
//            map.put(temorary.getCollectProductId(),temorary);
//        }
//        //生成新生成临时表
//        List<Long> newIds = temporaryList.stream()
//                .map(ErpAutoCollectProductTemporary::getId) // 假设getId是获取id的方法
//                .collect(Collectors.toList());
//        //获取已经临时表中已经存在的数据
//        List<ErpAutoCollectProductTemporary> queryTemporaryList = baseMapper.getInitializeLibraryListByCollectId(newIds);
//        List<Long> oldIds = queryTemporaryList.stream()
//                .map(ErpAutoCollectProductTemporary::getId) // 假设getId是获取id的方法
//                .collect(Collectors.toList());
//        //取两者的非交集进行批量插入
//        List<Long> nonIntersecting = newIds.stream()
//                .filter(num -> !oldIds.contains(num)) // 过滤出在list2中不存在的元素
//                .collect(Collectors.toList());
        if (temporaryList.size() > 0) {

            for (ErpAutoCollectProductTemporary product : temporaryList) {
                product.setProductType(1);
                ErpAutoCollectProductTemporary sel = baseMapper.selectOne(
                        new LambdaQueryWrapper<ErpAutoCollectProductTemporary>().eq(ErpAutoCollectProductTemporary::getCollectProductId, product.getCollectProductId())
                );
                if (ObjectUtils.isNull(sel)) {
                    baseMapper.insert(product);
                }
            }
        }
        return R.ok("执行完毕，插入" + temporaryList.size() + "条数据");
    }
}
